
<template>
    <div class="layout">
        <Layout :style="{ minHeight: '100vh', 'height': '100%' }">
            <Sider collapsible :collapsed-width="78" :width="256" v-model="isCollapsed" :class="navClass" class="sider"
                hide-trigger>
                <div class="left-top">
                    <a href="/">
                        <img src="@/assets/images/logo.fe4f63bf.png" alt="" v-if="theme === 'light'">
                        <img src="@/assets/images/logo-dark.1a60eea3.png" alt="" v-else>
                    </a>
                </div>
                <Menu :active-name="activeName" :open-names="openNames" @on-open-change="onOpenChange"
                    @on-select="onSelect" :theme="theme" width="auto" accordion :class="[menuitemClasses]"
                    style="height:100%" ref="menuRef">
                    <customMenuItem :data="menuList" />
                </Menu>
            </Sider>
            <Layout class="layout-container">
                <Header class="layout-header" :class="headerClass">
                    <div class="layout-header-left">
                        <div class="icon-is-collapsed hover-background" @click="isCollapsed = !isCollapsed">
                            <i class="iconfont icon-menu-fold" v-if="isCollapsed"></i>
                            <i class="iconfont icon-menu-unfold" v-else></i>
                        </div>
                        <Breadcrumb :style="{ margin: '16px 0' }">
                            <BreadcrumbItem>{{ $t('homeView.home') }}</BreadcrumbItem>
                            <BreadcrumbItem v-for="name, index in breadcrumbList" :key="index">
                                {{ name }}</BreadcrumbItem>
                        </Breadcrumb>
                    </div>
                    <div class="layout-header-right">
                        <div class="item reload hover-background">
                            <Icon type="ios-refresh" @click="toBlank"/>
                        </div>
                        <div class="item hover-background change-full-screen" @click="changeScreenfull">
                            <Icon type="md-contract" v-if="isFullscreen" />
                            <Icon type="md-expand" v-else />
                        </div>

                        <Dropdown trigger="hover">
                            <div class="user hover-background item">
                                <Avatar src="https://i.loli.net/2017/08/21/599a521472424.jpg" />
                                <i>admin</i>
                            </div>
                            <template #list>
                                <DropdownMenu>
                                    <DropdownItem @click="jump('')">
                                        <Icon type="ios-contact-outline" />
                                        <i style="font-style:normal;margin-left: 4px;">{{ $t("homeView.personal") }}</i>
                                    </DropdownItem>
                                    <DropdownItem @click="jump('')">
                                        <Icon type="ios-settings-outline" />
                                        <i style="font-style:normal;margin-left: 4px;">{{ $t("homeView.setting") }}</i>
                                    </DropdownItem>
                                    <!-- 分割线 -->
                                    <i
                                        style="height: 1px;width: 100%;display: block;background-color: #eee;margin: 4px 0;"></i>
                                    <DropdownItem @click="jump('login')">
                                        <Icon type="ios-log-in" />
                                        <i style="font-style:normal;margin-left: 4px;">{{ $t("homeView.loginOut") }}</i>
                                    </DropdownItem>
                                </DropdownMenu>
                            </template>
                        </Dropdown>
                        <div class="item hover-background">
                            <Language></Language>
                        </div>
                        <div class="set-style-icon hover-background item" @click="isDrawerShow = true">
                            <Icon type="md-more" />
                        </div>
                    </div>
                </Header>
                <Content :style="{ padding: '8px', flex: 1, overflowY: 'scroll' }" >
                    <div class="content-top">
                        <Tag type="dot" size="medium" :color="item.routeName == $route.name ? 'success' : ''"
                            :class="[item.routeName == $route.name ? 'tagClass' : '']" :closable="item.meta.isClose"
                            v-for="item, index in routerHistory" :key="item.routeName" @click="tagClick(item)"
                            @on-close="tagClose(item, index)">
                            {{ item.name }}</Tag>
                    </div>
                    <div class="router-view" v-watermark>
                        <router-view v-slot="{ Component }" v-if="isShowRouterView">
                            <keep-alive>
                                <component :is="Component"></component>
                            </keep-alive>
                        </router-view>
                        <customFooter></customFooter>
                    </div>
                </Content>
            </Layout>
        </Layout>
        <Drawer title="" :closable="false" width="280" v-model="isDrawerShow">
            <div class="content" style="padding:0 10px">
                <Divider>主题风格设置</Divider>
                <RadioGroup v-model="navClass" class="settheme">
                    <Radio :label="item.className" size="small"
                        v-for="item, index in globalStyleSettings.themeSetting.nav" :key="index"
                        @click="theme = item.theme">
                        <Tooltip :content="item.tiptitle" placement="top">
                            <img :src="item.imgUrl" alt="">
                        </Tooltip>
                    </Radio>
                </RadioGroup>
                <RadioGroup v-model="headerClass" class="settheme">
                    <Radio :label="item.className" size="small"
                        v-for="item, index in globalStyleSettings.themeSetting.header" :key="index">
                        <Tooltip :content="item.tiptitle" placement="top">
                            <img :src="item.imgUrl" alt="">
                        </Tooltip>
                    </Radio>
                </RadioGroup>
            </div>
        </Drawer>
        <BackTop :bottom="20" :height="30"></BackTop>
    </div>
</template>
<script setup lang="ts">
import { ref, toRef, computed, Ref, reactive, onMounted, nextTick, watch,provide } from 'vue'
import customFooter from '@/components/footer.vue'
import Language from '@/components/language.vue'
import screenfull from 'screenfull'
import { globalStyleSettings } from '@/global.config'
import { useRouter, useRoute } from 'vue-router'
import { removeToken } from '@/utils/auth'
import customMenuItem from '@/components/menuItem.vue'
import mainStore from '@/stores/main'
import otherStore from '@/stores/other'
const isShowRouterView = ref(true)
const routerViewReLoad = ()=>{
    isShowRouterView.value = false
    setTimeout(()=>{
        isShowRouterView.value = true
    },20)
}
const routerViewReLoadKey = Symbol('routerViewReLoad')
provide(routerViewReLoadKey,routerViewReLoad)
const $router = useRouter()
const $route = useRoute()
const $store = mainStore()
const $otherStore = otherStore()
// 菜单组件实例
const menuRef = ref<any>(null)
// 仓库中取出菜单主题
const theme: Ref<ThemeType> = toRef($store.menuInfo, 'theme')
// 菜单当前选项
const activeName = toRef($store.menuInfo, 'activeName')
// 子菜单打开 虽然 openNames 是数组 但开启了手风琴模式 只能打开一个子菜单
const openNames = toRef($store.menuInfo, 'openNames')
// routerHistory
const routerHistory = toRef($otherStore, 'routerHistory')
// 设置样式的抽屉
const isDrawerShow = ref<boolean>(false)
const isCollapsed = ref<boolean>(false) // 菜单是否折叠 
// 菜单class
const menuitemClasses = computed<Array<string>>(() => {
    return [isCollapsed.value ? 'collapsed-menu' : 'menu-item']
})
// 是否全屏
const isFullscreen = ref<boolean>(false)

// 主题class 动态设置
const navClass = toRef($store, 'navClass')
const headerClass = toRef($store, 'headerClass')
// 面包屑
const breadcrumbList = reactive<Array<string>>([])
// menu列表
const menuList = [
    {
        name: '1',
        icon: 'md-speedometer',
        title: 'Dashboard',
        children: [
            {
                name: '1-1',
                title: '主控台',
                routeName: 'console',
            }
        ]
    },
    {
        name: '2',
        icon: 'ios-paper',
        title: '内容管理',
        children: [
            {
                name: '2-1',
                title: '文章管理',
                routeName: 'articles',
            },
            {
                name: '2-2',
                title: '评论管理',
                routeName: 'comment',
            },
            {
                name: '2-3',
                title: '举报管理',
                routeName: 'report',
            }
        ]
    },
    {
        name: '3',
        icon: 'ios-people',
        title: '用户管理',
        children: [
            {
                name: '3-1',
                title: '新增用户',
                routeName: 'new-user'
            },
            {
                name: '3-2',
                title: '活跃用户',
                routeName: 'active-user'
            }
        ]
    },
    {
        name: '4',
        icon: 'ios-stats',
        title: '统计分析',
        children: [
            {
                name: '4-1',
                title: '新增和启动',

            },
            {
                name: '4-2',
                title: '活跃分析',
            },
            {
                name: '4-3',
                title: '时段分析',
            },
            {
                name: '4-4',
                title: '用户留存',
            },
            {
                name: '4-5',
                title: '流失用户',
            }
        ]
    },
    {
        name: '5',
        icon: 'ios-people',
        title: 'socket集成',
        children: [
            {
                name: '5-1',
                title: '聊天室',
                routeName: 'chat'
            }
        ]
    },
]
// 切换全屏
const changeScreenfull = () => {
    // 浏览器是否支持全屏
    if (screenfull.isEnabled) {
        screenfull.toggle()
        isFullscreen.value = !isFullscreen.value
    } else {
        isFullscreen.value = false
        screenfull.exit()
    }
}
// 点击tag 跳转
const tagClick = (item: RouterHistoryItemType) => {
    $router.push({ name: item.routeName })
    activeName.value = item.meta.menuName
    openNames.value = [item.meta.menuName.split('-')[0]]
    nextTick(() => {
        menuRef.value.updateActiveName();
        menuRef.value.updateOpened();
    })
}
// 点击tag 关闭
const tagClose = (item: RouterHistoryItemType, index: number) => {
    // 如果相等 则关闭当前路由 跳转到上一个 tag路由
    if ($route.name === item.routeName) {
        let perItem: RouterHistoryItemType = routerHistory.value[index - 1]
        $router.push({ name: routerHistory.value[index - 1].routeName })
        activeName.value = perItem.meta.menuName
        openNames.value = [perItem.meta.menuName.split('-')[0]]
        nextTick(() => {
            menuRef.value.updateActiveName();
            menuRef.value.updateOpened();
        })
    }
    routerHistory.value.splice(index, 1)
}
// 当前选择的菜单子项
const onSelect = (name: string) => {
    activeName.value = name
    breadcrumbList.length = 0 // 清空面包屑列表
    const item: ItemType | undefined = menuList.find((item: ItemType) => item.name == openNames.value[0])
    if (item && item.children) {
        breadcrumbList.push(item.title)
        item.children.forEach((sonItem: ItemType) => {
            if (sonItem.name == name) {
                // 添加面包屑
                breadcrumbList.push(sonItem.title)
                if (sonItem.routeName) {
                    // 跳转路由 并添加到路由历史中
                    $router.push({ name: sonItem.routeName }).then(() => {
                        // 路由已经跳转完毕
                        addRouterHistory()
                    })
                }
            }
        })
    } else if (item && item.routeName) {
        // 每次切换子菜单 添加路由历史 然后渲染tag 
        $router.push({ name: item.routeName }).then(() => {
            // 路由已经跳转完毕
            addRouterHistory()
        })
    }
}
// 重置面包屑 每次路由变化 重置面包屑
const resetBreadcrumb = () => {
    breadcrumbList.length = 0 // 清空面包屑列表
    const item: ItemType | undefined = menuList.find((item: ItemType) => item.name == openNames.value[0])
    if (item && item.children) {
        breadcrumbList.push(item.title)
        item.children.forEach((sonItem: ItemType) => {
            if (sonItem.name == activeName.value) {
                breadcrumbList.push(sonItem.title)
                return
            }
        })
    }
}

// 每次子菜单展开触发
const onOpenChange = (names: Array<string>): void => {
    openNames.value = names
}
// 添加路由历史的方法
const addRouterHistory = (): void => {
    let routeName = $route.name as string
    let index = routerHistory.value.findIndex((item) => routeName === item.routeName)
    // 如果路由历史已经有该路由信息 则先删除 并且添加到最后
    if (index !== -1) {
        routerHistory.value.splice(index, 1)
    }
    routerHistory.value.push({
        name: $route.meta.title as string,
        routeName,
        meta: $route.meta
    })
}
// 头像下拉列表跳转
const jump = (routeName: string) => {
    if (routeName === 'login') {
        removeToken()
        location.reload()
    }
}

// 刷新跳转到空白页
const toBlank = ()=>{
    $router.replace({
        path:'/blank',
        query:{
            redirect:$route.path
        }
    })
}
// 监听路由变化
watch(() => $route.name, resetBreadcrumb)
onMounted(() => {
    onSelect(activeName.value)
})
</script>

<style scoped lang="scss">
@import "@/styles/theme.class.module.scss";

.layout {
    height: 100%;

    .layout-container {
        display: flex;
        flex-direction: column;

        .content-top {
            ::v-deep(.ivu-tag-text) {
                color: #85888f;
            }

            .ivu-tag:hover {
                cursor: pointer;

                ::v-deep(.ivu-tag-text) {
                    color: #000;
                }
            }

            .tagClass {
                ::v-deep(.ivu-tag-text) {
                    color: #000;
                }
            }
        }

        .layout-header {
            display: flex;
            background: #fff;
            box-shadow: 0 2px 3px 2px rgba(0, 0, 0, .1);
            padding: 0;
            align-items: center;
            justify-content: space-between;

            .hover-background:hover {
                background-color: rgba($color: #f7f7f7, $alpha: 0.7);
                cursor: pointer;
            }

            .layout-header-left {
                display: flex;
                align-items: center;

                .icon-is-collapsed {
                    padding: 0 12px;
                    font-size: 18px;
                    margin-right: 15px;
                }

                ::v-deep(.ivu-breadcrumb>span:last-child) {
                    font-weight: 400;
                }
            }

            .layout-header-right {
                display: flex;
                align-items: center;

                .change-full-screen {
                    font-size: 20px;
                }

                .item {
                    padding: 0 10px;
                }
                .reload{
                    font-size: 30px;
                    align-items: center;
                    height: 100%;
                    justify-content: center;
                }


                .user {
                    display: flex;
                    align-items: center;

                    img {
                        width: 90%;
                        height: 90%;
                    }

                    i {
                        margin-left: 10px;
                        font-style: normal;
                    }

                    .divider {
                        height: 1px;
                        width: 100%;
                        display: block;
                        background-color: #eee;
                    }
                }

                .set-style-icon {
                    font-size: 20px;
                }
            }
        }

    }

    .sider {
        -webkit-box-shadow: 2px 0 8px 0 rgb(29 35 41 / 5%);
        box-shadow: 2px 0 8px 0 rgb(29 35 41 / 5%);

        .left-top {
            width: 100%;
            height: 64px;
            display: flex;
            border-bottom: 1px solid #101117;

            a {
                display: block;

                img {
                    width: 100%;
                }
            }
        }

        .menu-item span {
            display: inline-block;
            overflow: hidden;
            width: 69px;
            text-overflow: ellipsis;
            white-space: nowrap;
            vertical-align: bottom;
            transition: width .2s ease .2s;
        }

        ::v-deep(.ivu-menu-vertical.ivu-menu-light:after) {
            background: none;
        }

        ::v-deep(.collapsed-menu .ivu-menu-submenu-title-icon) {
            display: none;
        }

        ::v-deep(.collapsed-menu .ivu-menu-submenu-title) {
            font-size: 0px;
        }

        ::v-deep(.collapsed-menu .ivu-menu-child-item-active) {
            background: #101117;
        }

        ::v-deep(.collapsed-menu .ivu-menu-submenu-title) {
            width: 0px;
            transition: width .2s ease;
        }

        ::v-deep(.collapsed-menu i) {
            transform: translateX(5px);
            transition: font-size .2s ease .2s, transform .2s ease .2s;
            vertical-align: middle;
            font-size: 22px;
        }

        .rotate-icon {
            transform: rotate(-90deg);
        }
    }


}

.settheme {
    display: flex;
    flex-wrap: wrap;

    img {
        margin: 6px;
        cursor: pointer;
    }
}

::v-deep(.ivu-radio-group-item) {
    display: flex;
    flex-direction: column-reverse;
    align-items: center;
}
</style>